﻿using PMIS.Common.CustomAttribute;
using PMIS.Dialogs;
using PMIS.HttpRequest;
using PMIS.Views;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;

namespace PMIS
{
    public partial class App : PrismApplication
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void OnInitialized()
        {
            DialogParameters parameters = new DialogParameters
            {
                { KnownDialogParameters.WindowName, nameof(PanuonDialogWindow) }
            };
            var dialog = Container.Resolve<IDialogService>();
            dialog.ShowDialog(nameof(LoginView), parameters, callback =>
            {
                if (callback.Result != ButtonResult.OK)
                {
                    Environment.Exit(0);
                    return;
                }
                //IMPORTANT
                base.OnInitialized();
            });
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<HttpService>();
            containerRegistry.RegisterDialogWindow<PanuonDialogWindow>(nameof(PanuonDialogWindow));

            //注册导航页面
            RegisterNavigationPages(containerRegistry);

            //注册对话框页面
            RegisterDialog(containerRegistry);
        }

        public static void RegisterNavigationPages(IContainerRegistry containerRegistry)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            var pageTypes = assembly.GetTypes()
                .Where(t => t.GetCustomAttribute<NavigationAttribute>() != null && typeof(UserControl).IsAssignableFrom(t))
                .ToList();

            foreach (var pageType in pageTypes)
            {
                var attribute = pageType.GetCustomAttribute<NavigationAttribute>();
                containerRegistry.RegisterForNavigation(pageType, attribute?.Name);
            }
        }

        public static void RegisterDialog(IContainerRegistry containerRegistry)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            var pageTypes = assembly.GetTypes()
                .Where(t => t.GetCustomAttribute<DialogAttribute>() != null && typeof(UserControl).IsAssignableFrom(t))
                .ToList();

            foreach (var pageType in pageTypes)
            {
                var attribute = pageType.GetCustomAttribute<DialogAttribute>();
                containerRegistry.RegisterForNavigation(pageType, attribute?.Name);
            }
        }
    }
}
